package com.yzkj.cpjxc.business.service.impl;

import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.domain.Notification;
import com.yzkj.cpjxc.business.domain.NotificationQueryVo;
import com.yzkj.cpjxc.business.service.NotificationService;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NotificationServiceImpl implements NotificationService {

	/**
	 * MyBatis 命名空间
	 */
	private final static String MAPPER_NAMESPACE = "com.chkj.xezz.notification.mappers.NotificationMapper";

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	@Transactional
	@Override
	public BusinessMap create(Notification notification) throws Exception {
		BusinessMap bm = new BusinessMap();
		
		Date date = new Date();
		notification.setCreateTime(date);
		notification.setUpdateTime(date);
		notification.setIsActive(Constants.ACTIVE);
		
		sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".add", notification);
		return bm;
	}

	@Override
	public boolean isExists(Notification notification) throws Exception {
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExists", notification) > 0;
	}

	@Override
	public Notification getById(String uuid) throws Exception {
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getById", uuid);
	}

	@Transactional
	@Override
	public BusinessMap edit(Notification notification) throws Exception {
		BusinessMap bm = new BusinessMap();
		
		Date date = new Date();
		notification.setUpdateTime(date);
		
		sqlSessionTemplate.update(MAPPER_NAMESPACE + ".edit", notification);
		return bm;
	}

	@Transactional
	@Override
	public boolean falseDelete(String uuid) throws Exception {
		Notification n = new Notification();
		n.setUuid(uuid);
		n.setUpdateTime(new Date());
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".falseDeleteById", n);
		return true;
	}

	@Override
	public Pager<Notification> search(Pager<Notification> pager, NotificationQueryVo vo) throws Exception {
		List<Notification> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".page", vo, new RowBounds((pager.getCurrentPage() - 1) * pager.getLimit(), pager.getLimit()));
		pager.setDataList(dataList);

		// 如果需要转换成ShowVo展示，那么就在这里转换

		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getTotal", vo);
		pager.setTotal(total);
		return pager;
	}

}
